package com.foreknow.service;

import com.foreknow.dao.impl.UserDaoImpl;
import com.foreknow.entity.User;

import java.sql.SQLException;

public class UserService {
	private UserDaoImpl userDaoImpl;

	public UserService() {
		userDaoImpl = new UserDaoImpl();
	}

	public Boolean signUp(User user) {
		String sql = "insert into user(username,account,password,phone,email) values(?,?,?,?,?)";
		Object[] params = { user.getUsername(), user.getAccount(), user.getPassword(), user.getPhone(),
				user.getEmail() };
		try {
			return userDaoImpl.insert(sql, params) > 0;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	public Boolean signIn(String username, String password) {
		String sql = "select * from user Where username like ? or email like ? or account like ? or phone like ?";
		Object[] params = { username, username, username, username };
		User user;
		try {
			user = userDaoImpl.queryOne(sql, params);
			return password.equals(user.getPassword());
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} catch (NullPointerException e) {
			return false;
		}

	}

	public User getUserByName(String username) {
		String sql = "select * from user Where username like ? or email like ? or account like ? or phone like ?";
		Object[] params = { username, username, username, username };
		try {
			return userDaoImpl.queryOne(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public User getUserByID(Integer id) {
		String sql = "select * from user where id = ?";
		try {
			return userDaoImpl.queryOne(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	public Integer updateUser(User user) {
		String sql = "update user set username = ?, account = ?, password = ?, phone = ?, email = ? where id = ?";
		try {
			return userDaoImpl.update(sql, user.getUsername(),user.getAccount(),user.getPassword(),user.getPhone(),user.getEmail(),user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
	}
}
